package main

import (
	"context"
	"fmt"
	"gitee.com/DonHz/qimi/bluebell/config"
	"gitee.com/DonHz/qimi/bluebell/dao/mysql"
	"gitee.com/DonHz/qimi/bluebell/dao/redis"
	"gitee.com/DonHz/qimi/bluebell/routes"
	"gitee.com/DonHz/qimi/bluebell/util/logger"
	"gitee.com/DonHz/qimi/bluebell/util/snowflake"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// 1. 初始化配置文件
	if err:=config.Init(); err!=nil{
		fmt.Printf("init config failed, error: %v\n", err)
		return
	}
	// 2. 初始化日志
	if err:= logger.Init(config.Conf.LogConfig, config.Conf.Mode); err!=nil{
		fmt.Printf("init logger failed, error: %v\n", err)
		return
	}
	defer zap.L().Sync()
	zap.L().Debug("logger init success ...")
	// 3. 初始化Mysql连接
	mysql.Init(config.Conf.MysqlConfig)
	zap.L().Debug("mysql connect init success ...")
	// 4. 初始化Redis连接
	if err:=redis.Init(config.Conf.RedisConfig); err!=nil{
		fmt.Printf("init redis connect failed, error: %v\n", err)
		return
	}
	defer redis.Close()
	zap.L().Debug("redis connect init success ...")
	// 5. 雪花算法生成ID
	if err:=snowflake.Init(config.Conf.StartTime, config.Conf.MachineID); err!=nil {
		fmt.Printf("init snowflake failed, error: %v\n", err)
		return
	}
	zap.L().Debug("init snowflake success ...")
	// 5. 注册路由
	r:=routes.Setup()
	// 6. 启动服务
	srv:=&http.Server{
		Addr: fmt.Sprintf(":%d", viper.GetInt("port")),
		Handler: r,
	}
	go func() {
		if err:=srv.ListenAndServe(); err!=nil&& err!=http.ErrServerClosed {
			zap.L().Info("listen server failed", zap.Error(err))
		}
	}()

	//优雅关闭
	quit:=make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<- quit
	zap.L().Info("Shutdown Server ...")
	ctx, cancel:= context.WithTimeout(context.Background(), 5 * time.Second)
	defer cancel()
	if err:= srv.Shutdown(ctx); err!=nil{
		zap.L().Info("Server Showdown failed", zap.Error(err))
	}
	zap.L().Info("Server exiting. ")
}